package main

import (
	"fmt"
	"net"
	"strings"
)

func checkErr(err error) {
	if err != nil {
		panic(err.Error())
	}
}

func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println(r)
		}
	}()

	server, err := net.Listen("tcp", "127.0.0.1:51345")
	checkErr(err)
	defer server.Close()
	for {
		conn, err := server.Accept()
		fmt.Println(conn)
		checkErr(err)
		go recv(conn)
	}
}

func recv(conn net.Conn) {
	defer func() {
		if r := recover(); r != nil {
			return
		}
	}()
	defer conn.Close()
	buf := make([]byte, 1024)
	length, err := conn.Read(buf)
	checkErr(err)
	fmt.Println(string(buf[:length]))
	s := `
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
`
	conn.Write([]byte(s))

	for {
		length, err := conn.Read(buf)
		fmt.Println(string(buf[:length]))
		checkErr(err)
		s = strings.ToUpper(string(buf[:length]))
		go write(conn, &s)
	}
}

func write(conn net.Conn, s *string) {
	conn.Write([]byte(*s))
}
